package com.robot.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.robot.merchant.client.MemberClient;
import com.robot.merchant.pojo.MerchantMember;
import com.robot.merchant.pojo.Store;
import com.robot.merchant.pojo.client.Member;
import com.robot.merchant.service.MerchantMemberService;
import com.robot.merchant.service.StoreService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 店铺名下会员
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/merchantMember")
public class MerchantMemberController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MerchantMemberService merchantMemberService;
    @Autowired
    private StoreService storeService;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, merchantMemberService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.SUCCESS_QUERY, merchantMemberService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<MerchantMember> pageList = merchantMemberService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<MerchantMember>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, merchantMemberService.findSearch(searchMap));
    }

    /**
     * 通过storeId查找店铺名下的今日会员
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findTodayMembers/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findMerchantMembersByStoreIdOrderByRegisteredAtDescToday(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Page<MerchantMember> pageData = merchantMemberService.findMerchantMembersByStoreIdOrderByRegisteredAtDescToday(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 通过store_id查找店铺最近7日会员
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findWeekMembers/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findMerchantMembersByStoreIdOrderByRegisteredAtDescWeek(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Page<MerchantMember> pageData = merchantMemberService.findMerchantMembersByStoreIdOrderByRegisteredAtDescWeek(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 通过store_id查找店铺的总会员
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findTotalMembers/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findMerchantMembersByStoreIdOrderByRegisteredAtDescTotal(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Page<MerchantMember> pageData = merchantMemberService.findMerchantMembersByStoreIdOrderByRegisteredAtDescTotal(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * merchant端新增会员提醒
     *
     * @return
     */
    @RequestMapping(value = "newMemberReminder", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result newMemberReminder() {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Store storeInDb = storeService.findById(claims.getId());
        String message = storeService.checkStore(storeInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }


        String merchantMemberKey = "merchantMember_";
        List list = (List) redisTemplate.opsForList().rightPop(merchantMemberKey + claims.getId());
        if (list == null) {
            logger.info("merchantModule's newMemberReminder list is null");
            return new Result(StatusCode.SUCCESS_QUERY);
        }
        logger.info("merchantModule's newMemberReminder list is not null and list=" + list);
        Member memberInDb = JSON.parseObject(memberClient.thirdFindMemberById(list.get(0).toString()), Member.class);
        logger.info("merchantModule's newMemberReminder=" + memberInDb);
        if (memberInDb == null) {
            logger.info("merchantModule's newMemberReminder memberInDb is null");
            return new Result(StatusCode.SUCCESS_QUERY);
        }
        return new Result(StatusCode.SUCCESS_QUERY, memberInDb);
    }
}
